var OutHandover = function () {
  var template = /*html*/ `
    <div class="out-handover" v-loading.fullscreen.lock="loading">
      <div class="title" style="text-align:center;font-size:20px;margin-bottom:20px;">外协交接</div>
      <el-form :model="handover" label-width="100px">
        <el-form-item label="订单编号">
          <page-select filterable v-if="canSelectOrder" :options="orderList" v-model="handover.orderId" class="form-input" value-field="orderId" 
            label-field="orderId" popper-class="orderSelectPopover" :filter-method="orderFilterMehod">
            <template slot-scope="scope">
              <el-option v-for="order in scope.options" :key="order.orderId" :value="order.orderId" :label="order.orderId">
                <div class="out-handover-select-item">
                  <span style="width:145px;">{{order.orderId}}</span>
                  <span style="min-width:145px;">{{order.companyOrderId}}</span>
                  <span style="min-width:100px;">{{order.factoryId}}</span>
                  <span style="min-width:50px;">{{order.customerId}}</span>
                </div>
              </el-option>
            </template>
          </page-select>
          <span v-else>{{handover.orderId}}</span>
        </el-form-item>

        <template v-if="selectOrder!==null">
        <el-form-item label="公司订单编号">
          <span>{{selectOrder.companyOrderId}}</span>
        </el-form-item>
        <el-form-item label="工厂型号">
          <span>{{selectOrder.factoryId}}</span>
        </el-form-item>
        <el-form-item label="客户型号">
          <span>{{selectOrder.customerId}}</span>
        </el-form-item>
        </template>

        <el-form-item label="交接车间">
          <el-select filterable v-model="handover.workShop" class="form-input" value-key="id" :loading="handoverPosLoading">
            <el-option v-for="workShop in workShopList" :key="'ws_'+workShop.id" :value="workShop" :label="workShop.workshopName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="交接物料类型">
          <el-select filterable v-model="handover.materialType" class="form-input" :loading="materialTypeLoading">
            <el-option v-for="(material,index) in materialTypeList" :key="'material_'+index" :value="material.value" :label="material.label"></el-option>
          </el-select>
        </el-form-item>
        
        <template v-if="colorCountList!==null">
          <electroplate-out-handover v-if="handover.hasEle" ref="electroplateOrder" :handover="handover" :detail-list="colorCountList"></electroplate-out-handover>
          <material-out-handover v-else ref="materialOrder" :handover="handover" :detail-list="colorCountList"></material-out-handover>
        </template>

        <el-form-item label="备注">
          <el-input v-model="handover.remark" class="form-input" type="textarea" :autosize="true" resize="none"></el-input>
        </el-form-item>
      </el-form>
      <div style="text-align: center;">
        <el-button type="primary" @click="save">交接</el-button>
      </div>
    </div>
  `;

  return {
    props: {
      orderId: String
    },
    watch: {
      outOrderList: function () {
        this.resetOrderList();
      },
      'handover.orderId': function () {
        this.resetWorkShopList();
        this.resetMaterialTypeList();
        this.resetSelectOrder();
      },
      'handover.materialType': function () {
        this.resetColorCountList();
      }
    },
    data: function () {
      return {
        loading: false,
        handoverPosLoading: false,
        materialTypeLoading: false,
        canSelectOrder: this.orderId === undefined,
        handover: this.getInitHandover(),
        selectOrder: null,
        outOrderList: [],
        orderList: [],
        materialTypeList: [],
        workShopList: [],
        colorCountList: null,
        materialMachingMap: {}
      };
    },
    created: function () {
      this.loading = true;
      var self = this;
      Promise.all([
        this.setMaterialMachingMap(),
        this.setOrderList()
      ]).then(function () {
        self.loading = false;
        if (!self.canSelectOrder) {
          var orderId = self.handover.orderId;
          var orderList = self.orderList;
          var selectOrder = _.find(orderList, {
            orderId: orderId
          });
          if (selectOrder === undefined) {
            self.handover.orderId = '';
            self.canSelectOrder = true;
            return;
          }

          self.resetWorkShopList();
          self.resetMaterialTypeList();
          self.resetSelectOrder();
        }
      }).catch(function () {
        self.loading = false;
      });
    },
    methods: {
      getInitHandover: function () {
        var orderId = this.orderId;
        if (orderId === undefined) {
          orderId = '';
        }
        var handover = {
          orderId: orderId,
          materialType: '',
          hasEle: false,
          workShop: '',
          remark: ''
        };
        return handover;
      },

      setMaterialMachingMap: function () {
        var self = this;
        return ModuleUtil.getMaterialMachingInfoMap().then(function (materialMachingMap) {
          self.materialMachingMap = materialMachingMap;
          return materialMachingMap;
        }).catch(function () {
          return {};
        });
      },

      setOrderList: function () {
        var self = this;
        return ajaxRequest('putOutNew/getPutOutWarehouseCountOrder').then(function (outOrderList) {
          self.outOrderList = outOrderList;
          return outOrderList;
        }).catch(function () {
          return [];
        });
      },

      resetOrderList: function () {
        var outOrderList = this.outOrderList;
        var orderList = _.uniqBy(outOrderList, 'orderId');
        this.orderList = orderList;
      },

      resetWorkShopList: function () {
        var orderId = this.handover.orderId;
        var orderList = this.orderList;
        var order = _.find(orderList, {
          orderId: orderId
        });
        if (order === undefined) {
          this.handover.workShop = '';
          this.workShopList = [];
          return;
        }
        var frameType = order.frameType;
        var postData = {};
        if (frameType !== '多部门') {
          var deptId = order.deptId;
          postData.deptId = deptId;
        }
        var self = this;
        this.handoverPosLoading = true;
        ajaxRequest('basicData/getWorkshop', postData).then(function (workShopList) {
          self.workShopList = workShopList;
          self.handover.workShop = '';
          self.handoverPosLoading = false;
        }).then(function () {
          self.handoverPosLoading = false;
        });
      },

      resetMaterialTypeList: function () {
        var orderId = this.handover.orderId;
        if (orderId === '') {
          this.materialTypeList = [];
          this.handover.materialType = '';
          return;
        }

        this.materialTypeLoading = true;
        var self = this;
        this.setMaterialTypeList().then(function () {
          self.materialTypeLoading = false;
        });
      },

      setMaterialTypeList: function () {
        var self = this;
        var orderId = this.handover.orderId;
        return OrderApi.getOutOrderMachiningList(orderId).then(function (materialTypeList) {
          self.materialTypeList = materialTypeList;
          self.handover.materialType = '';
          return materialTypeList;
        }).catch(function () {
          return [];
        });
      },

      resetSelectOrder: function () {
        var orderId = this.handover.orderId;
        if (orderId === '') {
          this.selectOrder = null;
          return;
        }

        var orderList = this.orderList;
        var selectOrder = _.find(orderList, {
          orderId: orderId
        });
        this.selectOrder = selectOrder;
      },

      resetColorCountList: function () {
        var handover = this.handover;
        if (handover.materialType === '') {
          this.colorCountList = null;
          return;
        }

        var colorCountList = this.getColorList(handover);
        var eleColorList = _.filter(colorCountList, function (color) {
          return color.additionalMaterialType !== '';
        });

        if (eleColorList.length > 0) {
          colorCountList = eleColorList;
          handover.hasEle = true;
        } else {
          handover.hasEle = false;
        }
        this.colorCountList = colorCountList;
      },

      getColorList: function (handover) {
        var orderId = handover.orderId;
        var materialType = handover.materialType;
        var type;
        if (materialType === 'all') {
          type = -1;
        } else if (materialType.indexOf('machineMap-') === 0) {
          type = materialType.split('-')[1];
          type = Number(type);
        } else {
          type = 0;
        }
        var orderList = this.outOrderList;
        if (type === 0) {
          orderList = _.filter(orderList, {
            orderId: orderId,
            materialType: materialType
          });
          return orderList;
        }

        if (type === -1) {
          orderList = _.filter(orderList, {
            orderId: orderId
          });
        } else {
          var materialMachingMap = this.materialMachingMap;
          var obj = materialMachingMap[type];
          if (obj === undefined) {
            return [];
          }

          var materialTypeList = obj.materialTypeList;
          orderList = _.filter(orderList, function (order) {
            var materialType = order.materialType;
            return materialTypeList.indexOf(materialType) !== -1 && order.orderId === orderId;
          });
        }
        return orderList;
      },

      orderFilterMehod: function (options, queryValue) {
        if (queryValue === '') {
          return options;
        }

        queryValue = queryValue.toLowerCase();
        var filterParams = ['orderId', 'companyOrderId', 'factoryId', 'customerId'];
        options = _.filter(options, function (option) {
          for (var i = 0; i < filterParams.length; i++) {
            var filterParam = filterParams[i];
            var value = _.get(option, filterParam, '');
            if (value === null) {
              value = '';
            }
            if (typeof value === 'string') {
              value = value.toLowerCase();
            }
            if (value.indexOf(queryValue) !== -1) {
              return true;
            }
          }
          return false;
        });
        return options;
      },

      save: function () {
        var handover = this.handover;
        var postData = this.getHandoverObject(handover);
        if (postData === null) {
          return;
        }

        this.loading = true;
        var self = this;
        ajaxRequest('putOutNew/putOutWarehouseToWorkshopOrWarehouse', {
          jsonArray: JSON.stringify(postData)
        }).then(function () {
          self.loading = false
          self.$alert('外协交接成功', '信息', {
            callback: function () {
              if (self.canSelectOrder) {
                self.handover = self.getInitHandover();
              }
              self.$emit('save-success', handover);
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      getHandoverObject: function (handover) {
        var fields = ['orderId', 'workShop', 'materialType'];
        var postObj = {
          source: 1
        };

        for (var i = 0; i < fields.length; i++) {
          var field = fields[i];
          var value = handover[field];
          if (SysUtil.isEmpty(value)) {
            this.$alert(i18n.getMsg(`orderCirculation.outHandover.${field}`), '信息');
            return null;
          }
          postObj[field] = value;
        }

        var workShop = handover.workShop;
        delete postObj.workShop;
        postObj.workShopId = workShop.id;
        postObj.sourceName = workShop.workshopName;
        postObj.remark = handover.remark;

        var colors = null;
        if (handover.hasEle) {
          colors = this.$refs.electroplateOrder.getPostData();
        } else {
          colors = this.$refs.materialOrder.getPostData();
        }

        if (colors === null) {
          return null;
        }

        var maching = handover.materialType;
        var type;
        if (maching === 'all') {
          type = -1;
        } else if (maching.indexOf('machineMap-') === 0) {
          type = maching.split('-')[1];
          type = Number(type);
        } else {
          type = 0;
        }
        postObj.type = type;

        var postData = _.map(colors, function (color) {
          var obj = _.cloneDeep(postObj);
          _.assignIn(obj, color);
          return obj;
        });
        return postData;
      }
    },
    components: {
      PageSelect: PageSelect,
      MaterialOutHandover: MaterialOutHandover(true),
      ElectroplateOutHandover: ElectroplateOutHandover
    },
    template: template
  };
}();
